<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redis;
use common\utils\RedisKeys;

class HallDomainService
{
    // 根据域名获取hall_id
    public static function getHallID()
    {
        // 开发,单元测试模式
        if (env('APP_ENV') == 'dev' || env('APP_ENV') == 'testing') {
            return config('database.defaultHallID');
        }
        // 获取域名
        $domain = Request::server('HTTP_HOST');
        $domain = preg_replace('/:(.*)$/', '', $domain);
        // 先查缓存
        $redis = Redis::connection('master');
        $key = RedisKeys::DOMAIN_KEY . $domain;
        $hall_id = $redis->get($key);
        if ($hall_id) {
            return $hall_id;
        }
        // 不存在再查数据库
        $hd = DB::table('hall_domain')->where(['domain' => $domain])->first();
        if ($hd) {
            $hall_id = $hd['hall_id'];
            $redis->set($key, $hall_id);
            return $hall_id;
        }
        // 找不到直接抛异常
        return error_exit(400, "Error Domain");
    }
}
